package com.fly.demo.service.impl;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;

import com.fly.demo.entity.Article;
import com.fly.demo.entity.BlogData;
import com.fly.demo.service.DataInitor;

import lombok.extern.slf4j.Slf4j;

/**
 * 通过WebApi接口初始化
 */
@Slf4j
@Order(2)
@Component
public class WebApiDataInitor implements DataInitor
{
    @Autowired
    WebClient webClient;
    
    @Override
    public boolean init(List<Article> articles)
    {
        try
        {
            log.info("start init...");
            BlogData blogData = webClient.get()
                .uri("https://00fly.online/upload/data.json")
                .acceptCharset(StandardCharsets.UTF_8)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(BlogData.class)
                .timeout(Duration.ofSeconds(10)) // 单独设置超时
                .block();
            if (blogData != null)
            {
                articles.addAll(blogData.getData().getList());
            }
            return !CollectionUtils.isEmpty(articles);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
            return false;
        }
    }
}